﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;
using System.IO;
using CTEM.Models;
using CTEM.Controllers.Global;
using CTEM.Controllers.Global;
using System.Diagnostics;

namespace CTEM.Controllers.DAO
{
    public class CT_PurchaseBookDAO
    {
        /// <summary>
        /// 
        /// </summary>
        public CT_PurchaseBookDAO()
        {
            Transaction = null;
        }

        /// <summary>
        /// 
        /// </summary>
        public SqlTransaction Transaction { get; set; }

        /// <summary>
        /// 
        /// </summary>
        private StackFrame _currentStackFrame;

        /// <summary>
        /// 
        /// </summary>
        private SqlConnection _con;

        /// <summary>
        /// 
        /// </summary>
        SqlConnection Connection
        {
            get
            {
                if (_con == null)
                    _con = new SqlConnection(DatabaseInfo.ConnectionString);
                if (_con.State == ConnectionState.Closed)
                {
                    _con.Open();
                }
                return _con;
            }
            set
            {
                _con = value;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="purbook"></param>
        /// <returns></returns>
        public long CreatePurchaseBook(CT_PurchaseBookDTO purbook)
        {
            _currentStackFrame = new StackFrame();
            using (var cmd = new SqlCommand("[dbo].[CT_CreatePurchaseBook]", Connection) { CommandType = CommandType.StoredProcedure })
            {
                if (Transaction != null)
                {
                    cmd.Transaction = Transaction;
                }
                try
                {
                    string[] parameternames = { "@DebtID", 
                                                  "@DatePurchase", 
                                                  "@Officer", 
                                                  "@VehicleID", 
                                                  "@ConstructionID", 
                                                  "@WarehouseID", 
                                                  "@Contents", 
                                                  "@MaterialID", 
                                                  "@GroupMaterialID", 
                                                  "@Quantity", 
                                                  "@Price", 
                                                  "@TotalCost", 
                                                  "@IsPay", 
                                                  "@IsConfirm", 
                                                  "@Note", 
                                                  "@CreatedBy", 
                                                  "@CreatedDate", 
                                                  "@ComparationDebtID" };
                    object[] parametervalues = { purbook.DebtID, 
                                                   purbook.DatePurchase, 
                                                   purbook.Officer, 
                                                   purbook.VehicleID, 
                                                   purbook.ConstructionID, 
                                                   purbook.WarehouseID, 
                                                   purbook.Contents, 
                                                   purbook.MaterialID, 
                                                   purbook.GroupMaterialID, 
                                                   purbook.Quantity, 
                                                   purbook.Price,
                                                   purbook.TotalCost,
                                                   purbook.IsPay,
                                                   purbook.IsConfirm,
                                                   purbook.Note,
                                                   purbook.CreatedBy,
                                                   purbook.CreatedDate,
                                                   purbook.ComparationDebtID };
                    cmd.Parameters.AddRange(Global.Global.SetSqlParameter(parameternames, parametervalues));
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                            return Convert.ToInt64(reader[0]);
                    }
                    return 0;
                }
                catch (SqlException sql)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, sql.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return 0;
                }
                catch (Exception e)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, e.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return 0;
                }
                finally
                {
                    if (Transaction == null)
                        Connection.Close();
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="purbook"></param>
        /// <returns></returns>
        public bool UpdatePurchaseBook(CT_PurchaseBookDTO purbook)
        {
            _currentStackFrame = new StackFrame();
            using (var cmd = new SqlCommand("[dbo].[CT_UpdatePurchaseBook]", Connection) { CommandType = CommandType.StoredProcedure })
            {
                if (Transaction != null)
                {
                    cmd.Transaction = Transaction;
                }
                try
                {
                    string[] parameternames = { "@PurchaseBookID",
                                                  "@DebtID", 
                                                  "@DatePurchase", 
                                                  "@Officer", 
                                                  "@VehicleID", 
                                                  "@ConstructionID", 
                                                  "@WarehouseID", 
                                                  "@Contents", 
                                                  "@MaterialID", 
                                                  "@GroupMaterialID", 
                                                  "@Quantity", 
                                                  "@Price", 
                                                  "@TotalCost", 
                                                  "@IsPay", 
                                                  "@IsConfirm", 
                                                  "@Note", 
                                                  "@UpdatedBy", 
                                                  "@LastUpdated", 
                                                  "@ComparationDebtID" };
                    object[] parametervalues = { purbook.PurchaseBookID,
                                                   purbook.DebtID, 
                                                   purbook.DatePurchase, 
                                                   purbook.Officer, 
                                                   purbook.VehicleID, 
                                                   purbook.ConstructionID, 
                                                   purbook.WarehouseID, 
                                                   purbook.Contents, 
                                                   purbook.MaterialID, 
                                                   purbook.GroupMaterialID, 
                                                   purbook.Quantity, 
                                                   purbook.Price,
                                                   purbook.TotalCost,
                                                   purbook.IsPay,
                                                   purbook.IsConfirm,
                                                   purbook.Note,
                                                   purbook.UpdatedBy,
                                                   purbook.LastUpdated,
                                                   purbook.ComparationDebtID };
                    cmd.Parameters.AddRange(Global.Global.SetSqlParameter(parameternames, parametervalues));
                    cmd.ExecuteReader();
                    return true;
                }
                catch (SqlException sql)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, sql.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return false;
                }
                catch (Exception e)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, e.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return false;
                }
                finally
                {
                    if (Transaction == null)
                        Connection.Close();
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="consDTO"></param>
        /// <returns></returns>
        public bool DeletePurchaseBook(long pubbookID)
        {
            _currentStackFrame = new StackFrame();
            using (var cmd = new SqlCommand("[dbo].[CT_DeletePurchaseBook]", Connection) { CommandType = CommandType.StoredProcedure })
            {
                if (Transaction != null)
                {
                    cmd.Transaction = Transaction;
                }
                try
                {
                    cmd.Parameters.Add(new SqlParameter("@PurchaseBookID", pubbookID));
                    cmd.ExecuteNonQuery();
                    return true;
                }
                catch (SqlException sql)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, sql.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return false;
                }
                catch (Exception e)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, e.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return false;
                }
                finally
                {
                    if (Transaction == null)
                        Connection.Close();
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="purbookID"></param>
        /// <returns></returns>
        public CT_PurchaseBookDTO GetPurchaseBookByID(long purbookID)
        {
            _currentStackFrame = new StackFrame();
            using (var cmd = new SqlCommand("[dbo].[CT_GetPurchaseBookByID]", Connection))
            {
                if (Transaction != null)
                {
                    cmd.Transaction = Transaction;
                }
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(new SqlParameter("@PurchaseBookID", purbookID));
                try
                {
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            CT_PurchaseBookDTO purbookDTO = new CT_PurchaseBookDTO
                            {
                                PurchaseBookID = Convert.ToInt64(reader["PurchaseBookID"]),
                                DebtID = Convert.ToInt64(reader["DebtID"]),
                                DatePurchase = Convert.ToDateTime(reader["DatePurchase"]),
                                Officer = Convert.ToString(reader["Officer"]),
                                VehicleID = Convert.ToInt64(reader["VehicleID"]),
                                ConstructionID = Convert.ToInt64(reader["ConstructionID"]),
                                WarehouseID = Convert.ToInt64(reader["WarehouseID"]),
                                Contents = Convert.ToString(reader["Contents"]),
                                MaterialID = Convert.ToInt64(reader["MaterialID"]),
                                GroupMaterialID = Convert.ToInt64(reader["GroupMaterialID"]),
                                Quantity = Convert.ToDouble(reader["Quantity"]),
                                Unit = Convert.ToString(reader["Unit"]),
                                Price = Convert.ToInt64(reader["Price"]),
                                TotalCost = Convert.ToInt64(reader["TotalCost"]),
                                IsPay = Convert.ToBoolean(reader["IsPay"]),
                                IsConfirm = Convert.ToBoolean(reader["IsConfirm"]),
                                Note = Convert.ToString(reader["Note"]),
                                CreatedBy = Convert.ToString(reader["CreatedBy"]),
                                CreatedDate = Convert.ToDateTime(reader["CreatedDate"]),
                                UpdatedBy = Convert.ToString(reader["UpdatedBy"]),
                                LastUpdated = Convert.ToDateTime(reader["LastUpdated"]),
                                ComparationDebtID = Convert.ToInt64(reader["ComparationDebtID"])
                            };
                            return purbookDTO;
                        }
                        return null;
                    }
                }
                catch (SqlException sql)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, sql.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return null;
                }
                catch (Exception e)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, e.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return null;
                }
                finally
                {
                    if (Transaction == null)
                        Connection.Close();
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public List<CT_PurchaseBookDTO> LoadAllPurchaseBooks()
        {
            _currentStackFrame = new StackFrame();
            using (var cmd = new SqlCommand("[dbo].[CT_GetAllPurchaseBook]", Connection))
            {
                if (Transaction != null)
                {
                    cmd.Transaction = Transaction;
                }
                cmd.CommandType = CommandType.StoredProcedure;
                try
                {
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        List<CT_PurchaseBookDTO> listpubbook = new List<CT_PurchaseBookDTO>();
                        while (reader.Read())
                        {
                            CT_PurchaseBookDTO pubbookDTO = new CT_PurchaseBookDTO
                            {
                                PurchaseBookID = Convert.ToInt64(reader["PurchaseBookID"]),
                                DebtID = Convert.ToInt64(reader["DebtID"]),
                                DatePurchase = Convert.ToDateTime(reader["DatePurchase"]),
                                Officer = Convert.ToString(reader["Officer"]),
                                VehicleID = Convert.ToInt64(reader["VehicleID"]),
                                ConstructionID = Convert.ToInt64(reader["ConstructionID"]),
                                WarehouseID = Convert.ToInt64(reader["WarehouseID"]),
                                Contents = Convert.ToString(reader["Contents"]),
                                MaterialID = Convert.ToInt64(reader["MaterialID"]),
                                GroupMaterialID = Convert.ToInt64(reader["GroupMaterialID"]),
                                Quantity = Convert.ToDouble(reader["Quantity"]),
                                Unit = Convert.ToString(reader["Unit"]),
                                Price = Convert.ToInt64(reader["Price"]),
                                TotalCost = Convert.ToInt64(reader["TotalCost"]),
                                IsPay = Convert.ToBoolean(reader["IsPay"]),
                                IsConfirm = Convert.ToBoolean(reader["IsConfirm"]),
                                Note = Convert.ToString(reader["Note"]),
                                CreatedBy = Convert.ToString(reader["CreatedBy"]),
                                CreatedDate = Convert.ToDateTime(reader["CreatedDate"]),
                                UpdatedBy = Convert.ToString(reader["UpdatedBy"]),
                                LastUpdated = Convert.ToDateTime(reader["LastUpdated"]),
                                ComparationDebtID = Convert.ToInt64(reader["ComparationDebtID"])
                            };
                            listpubbook.Add(pubbookDTO);
                        }
                        return listpubbook;
                    }
                }
                catch (SqlException sql)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, sql.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return null;
                }
                catch (Exception e)
                {
                    string msn = Global.Global.LogMessage(_currentStackFrame.GetFileName(), _currentStackFrame.GetMethod().Name, e.Message);
                    Logger.WriteLog(LogLevel.ERROR, msn);
                    return null;
                }
                finally
                {
                    if (Transaction == null)
                        Connection.Close();
                }
            }
        }
    }
}
